const mysql = require('mysql2/promise');

async function verifyMapHierarchy () {
  const connection = await mysql.createConnection({
    host: '43.143.253.188',
    port: 3306,
    user: 'nextjs',
    password: 'yEAiRE2jcxTyRBy5',
    database: 'nextjs',
    timezone: '+08:00'
  });

  try {
    console.log('🔍 验证地图层级关系...\n');

    // 根据WebSocket数据定义的完整层级关系
    const expectedHierarchy = {
      // 魏国 (areaId: 100)
      100: {
        name: '魏国',
        children: {
          289: { name: '许昌', children: [2, 301, 487, 533] }, // 新手村、陈留、九里山、芒砀山
          302: { name: '洛阳', children: [285, 286, 333, 337] }, // 官渡、虎牢关、乌巢、函谷关
          304: { name: '长安', children: [303, 311, 414] } // 华山、潼关、五丈原
        }
      },
      // 蜀国 (areaId: 19)
      19: {
        name: '蜀国',
        children: {
          70: { name: '成都', children: [93, 112, 113] }, // 落凤坡、广汉、峨眉山
          111: { name: '南中', children: [52, 143, 351] }, // 云南、泸水、西洱湖
          117: { name: '汉中', children: [306, 307, 308] } // 子午谷、街亭、上方谷
        }
      },
      // 吴国 (areaId: 43)
      43: {
        name: '吴国',
        children: {
          154: { name: '建业', children: [267] }, // 广陵
          212: { name: '长沙', children: [220, 221, 222] }, // 巴陵、洞庭湖、湘水
          264: { name: '江陵', children: [137, 161, 163] } // 麦城、长坂坡、夷陵
        }
      }
    };

    // 等级信息映射
    const expectedLevels = {
      2: '(1级)', 301: '(5级)', 487: '(20级)', 533: '(30级)',
      285: '(40级)', 286: '(50级)', 333: '(80级)', 337: '(55级)',
      303: '(90级)', 311: '(75级)', 414: '(65级)',
      93: '(30级)', 112: '(40级)', 113: '(50级)',
      52: '(60级)', 143: '(70级)', 351: '(80级)',
      306: '(90级)', 307: '(100级)', 308: '(120级)',
      222: '(130级)', 137: '(140级)', 161: '(140级)'
    };

    let totalErrors = 0;
    let totalVerified = 0;

    console.log('📊 验证顶级区域...');
    for (const [areaId, areaData] of Object.entries(expectedHierarchy)) {
      const [area] = await connection.execute(
        'SELECT id, name, parent_id FROM map_areas WHERE id = ?',
        [areaId]
      );

      if (area.length === 0) {
        console.log(`  ❌ 顶级区域不存在: ${areaData.name} (ID: ${areaId})`);
        totalErrors++;
      } else if (area[0].parent_id !== null) {
        console.log(`  ❌ 顶级区域父级错误: ${areaData.name} (ID: ${areaId}) - 父级应为NULL，实际为${area[0].parent_id}`);
        totalErrors++;
      } else {
        console.log(`  ✅ 顶级区域正确: ${areaData.name} (ID: ${areaId})`);
        totalVerified++;
      }
    }

    console.log('\n📊 验证二级城市...');
    for (const [areaId, areaData] of Object.entries(expectedHierarchy)) {
      for (const [cityId, cityData] of Object.entries(areaData.children)) {
        const [city] = await connection.execute(
          'SELECT id, name, parent_id FROM map_areas WHERE id = ?',
          [cityId]
        );

        if (city.length === 0) {
          console.log(`  ❌ 二级城市不存在: ${cityData.name} (ID: ${cityId})`);
          totalErrors++;
        } else if (city[0].parent_id !== parseInt(areaId)) {
          console.log(`  ❌ 二级城市父级错误: ${cityData.name} (ID: ${cityId}) - 父级应为${areaId}，实际为${city[0].parent_id}`);
          totalErrors++;
        } else {
          console.log(`  ✅ 二级城市正确: ${cityData.name} (ID: ${cityId}) -> 父级: ${areaData.name} (ID: ${areaId})`);
          totalVerified++;
        }
      }
    }

    console.log('\n📊 验证三级区域...');
    for (const [areaId, areaData] of Object.entries(expectedHierarchy)) {
      for (const [cityId, cityData] of Object.entries(areaData.children)) {
        for (const childId of cityData.children) {
          const [child] = await connection.execute(
            'SELECT id, name, parent_id, extension FROM map_areas WHERE id = ?',
            [childId]
          );

          if (child.length === 0) {
            console.log(`  ❌ 三级区域不存在: ID ${childId}`);
            totalErrors++;
          } else if (child[0].parent_id !== parseInt(cityId)) {
            console.log(`  ❌ 三级区域父级错误: ${child[0].name} (ID: ${childId}) - 父级应为${cityId}，实际为${child[0].parent_id}`);
            totalErrors++;
          } else {
            const expectedLevel = expectedLevels[childId];
            const actualLevel = child[0].extension;
            const levelStatus = expectedLevel ?
              (actualLevel === expectedLevel ? '✅' : `❌ 等级错误(期望:${expectedLevel},实际:${actualLevel})`) :
              (actualLevel ? '⚠️ 多余等级' : '✅');

            console.log(`  ${levelStatus} 三级区域: ${child[0].name} (ID: ${childId}) -> 父级: ${cityData.name} (ID: ${cityId})`);
            totalVerified++;
          }
        }
      }
    }

    // 显示完整的层级结构
    console.log('\n📊 完整层级结构验证:');
    for (const [areaId, areaData] of Object.entries(expectedHierarchy)) {
      console.log(`\n${areaData.name} (ID: ${areaId}):`);

      for (const [cityId, cityData] of Object.entries(areaData.children)) {
        const [cityInfo] = await connection.execute(
          'SELECT id, name, parent_id, extension FROM map_areas WHERE id = ?',
          [cityId]
        );

        if (cityInfo.length > 0) {
          const city = cityInfo[0];
          const cityName = city.extension ? `${city.name}${city.extension}` : city.name;
          console.log(`  └─ ${cityName} (ID: ${cityId}, 父级: ${city.parent_id})`);

          // 显示子区域
          const [children] = await connection.execute(
            'SELECT id, name, parent_id, extension FROM map_areas WHERE parent_id = ? ORDER BY id',
            [cityId]
          );

          children.forEach(child => {
            const childName = child.extension ? `${child.name}${child.extension}` : child.name;
            console.log(`    └─ ${childName} (ID: ${child.id})`);
          });
        }
      }
    }

    // 统计信息
    console.log('\n📊 验证统计:');
    console.log(`  验证通过: ${totalVerified} 个区域`);
    console.log(`  验证失败: ${totalErrors} 个区域`);

    if (totalErrors === 0) {
      console.log('\n🎉 所有层级关系验证通过！地图数据结构完全符合WebSocket通信要求！');
    } else {
      console.log(`\n⚠️ 发现 ${totalErrors} 个问题，请检查上述错误信息。`);
    }

  } catch (error) {
    console.error('❌ 验证失败:', error.message);
    if (error.code) {
      console.error('错误代码:', error.code);
    }
  } finally {
    await connection.end();
    console.log('\n🔌 数据库连接已关闭');
  }
}

// 运行脚本
if (require.main === module) {
  verifyMapHierarchy().catch(console.error);
}

module.exports = { verifyMapHierarchy };
